﻿using System;
using System.Configuration;

namespace CodeBook
{
   public static class ConfigHelper
    {
       
        /// <summary>
        /// 获取或者设置指定路径的config文件
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string Config(string key, string value,string path = "Admin")
        {
            try
            {
                string url = AppDomain.CurrentDomain.BaseDirectory + path + "\\App.config";
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = url;// @"F:\App.config";
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                //string connstr = config.ConnectionStrings.ConnectionStrings["appSettings"].ConnectionString;//获取连接字符串                
                if (!string.IsNullOrEmpty(value))
                {
                    config.AppSettings.Settings[key].Value = value;
                    config.Save();
                }
                return config.AppSettings.Settings[key].Value;
            }
            catch (Exception)
            {

                return "";
            }
        }
        /// <summary>
        /// 根目录配置文件
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string Config(string key,string value="")
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
                if (!string.IsNullOrEmpty(value))
                {
                    config.AppSettings.Settings[key].Value = value;
                    config.Save();
                }
                return config.AppSettings.Settings[key].Value;
            }
            catch (Exception)
            {

                return "";
            }
        }
    }
}
